﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Timers;

namespace ComUIControl
{
    public partial class TipImageBox : UserControl
    {
        public TipImageBox()
        {
            this.Visible = false;
            InitializeComponent();
            InitTimer();
        }

        private Bitmap _image;
        public Bitmap Image
        {
            get
            {
                return _image;
            }
            set
            {
                if(_image != value)
                {
                    pictureBox1.Image = value;
                    _image = value;
                }                             
            }
        }

        private System.Timers.Timer timer;
        private SynchronizationContext context;
        private void InitTimer()
        {
            context = SynchronizationContext.Current;
            timer = new System.Timers.Timer();
            timer.Interval = 3 * 1000;
            timer.AutoReset = false;
            timer.Elapsed += Timer_Elapsed;
        }

        private void Timer_Elapsed(object o, ElapsedEventArgs e)
        {
            context.Post(delegate
            {
                if (this.Visible)
                {
                    this.Visible = false;
                    timer.Stop();
                }
            }, null);
        }
        public delegate void ShowTitpImageDelegate(Bitmap img, Point p);
        public void Show(Bitmap img, Point p)
        {
            if (this.InvokeRequired)
            {
                ShowTitpImageDelegate outdelegate = new ShowTitpImageDelegate(Show);
                this.BeginInvoke(outdelegate, new object[] { img, p });
                return;
            }
            timer.Stop();
            this.Size = img.Size;
            this.Location = p;
            Image = img;
            this.Visible = true;
            pictureBox1.Invalidate();
            timer.Start();
        }

        public delegate void HideDelegate();
        public void RemainHidden()
        {
            if (this.InvokeRequired)
            {
                HideDelegate outdelegate = new HideDelegate(RemainHidden);
                this.BeginInvoke(outdelegate, new object[] { });
                return;
            }
            timer.Stop();
            this.Visible = false;
            Image = null;
        }
    }
}
